<template>
<el-row :class="full === false?'nofull':'full'">
    <el-col :class="full === false?'editor-tool editor-tool-position':'editor-tool'" :span="24">
      <!-- 标题 -->
      <div class="editor-tool-icon" @click="setTag(null,'# ')"><b>h1</b></div>
      <div class="editor-tool-icon" @click="setTag(null,'## ')"><b>h2</b></div>
      <div class="editor-tool-icon" @click="setTag(null,'### ')"><b>h3</b></div>
      <div class="editor-tool-icon" @click="setTag(null,'#### ')"><b>h4</b></div>
      <div class="editor-tool-icon" @click="setTag(null,'##### ')"><b>h5</b></div>
      <!-- 代码块 -->
      <el-popover
        placement="bottom"
        title="选择语言"
        :width="200"
        trigger="click"
      >
        <template #reference>
          <div class="editor-tool-icon">code</div>
        </template>
        <el-select
        v-model="CodeOptionsValue"
        filterable
        placeholder="请选择"
        @change="setCode"
        >
          <el-option
            v-for="item in CodeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-popover>
      <!-- 图片功能 -->
      <i class="el-icon-picture" @click="UploadDialogVisible = true"></i>
      <!--  上传附件 -->
      <i class="el-icon-paperclip" @click="UploadFile" ></i>
      <!-- 字体样式 -->
      <div class="editor-tool-icon" @click="setTag(1,'*')">I</div>
      <div class="editor-tool-icon" @click="setTag(2,'**')"><b>B</b></div>
      <div class="editor-tool-icon" @click="setTag(1,'`')"><b>＊</b></div>
      <div class="editor-tool-icon" @click="setTag(null,'\r\n> ')"><b>“</b></div>
      <i :class="full === false?'el-icon-full-screen':'el-icon-switch-button'" @click="full = !full"></i>
    </el-col>
    <el-col :span="12" class="text-content">
      <textarea
      class="editor-content"
      id="editor-content"
      @input="setContent"
      v-model="content.noBuild"></textarea>
    </el-col>
    <el-col :span="12" class="text-content">
      <div id="editor-build-content" class="editor-build-content markdown-body" v-html="content.build"></div>
    </el-col>
</el-row>

  <UploadDialog
  :UploadDialogVisible="UploadDialogVisible"
  :CheckLimit="null"
  :Checked="Checked"
  @SaveUploadFile="SaveUploadFile"
  @CancelUploadFile="CancelUploadFile"
  />
</template>
<script>
import 'github-markdown-css/github-markdown.css'
import 'highlight.js/styles/xcode.css'
import UploadDialog from '@/components/upload/upload-file-dialog';
import { BASE_IMAGE_URL } from '@/utils/config';
import { reactive,ref,getCurrentInstance } from 'vue'
export default {
  name:"MarkDownEditor",
  components: {
    UploadDialog
  },
  props:{
    Content:{
      type: Object,
      default: () =>{}
    }
  },
  setup(props, { emit, attrs }){
    // 是否全屏
    let full = ref(false)
    let { ctx } = getCurrentInstance();
    // 默认内容
    let content = reactive({
      noBuild:props.Content.toString(),
      build:""
    })
    // 代码块类型下拉
    let CodeOptions = [
      {value:"go",label:"go"},
      {value:"javascript",label:"javascript"},
      {value:"php",label:"php"},
      {value:"html",label:"html"},
      {value:"css",label:"css"},
      {value:"vue",label:"vue"},
      {value:"json",label:"json"},
      {value:"xml",label:"xml"},
      {value:"java",label:"java"},
      {value:"c#",label:"c#"},
      {value:"c++",label:"c++"},
      {value:".net",label:".net"},
    ]
    let CodeOptionsValue = reactive("")
    // 图片上传相关
    let Checked = reactive([])
    let UploadDialogVisible = ref(false)
    // 选择图库图片
    function SaveUploadFile(){
      UploadDialogVisible.value = false
      let pos =   getPositionStartAndEnd();
      // 多图渲染
      if(Checked.length > 1)
      {
        for(let i = 0; i < Checked.length; i++)
        {
          let str = eval('/([\\w\\W]{' + pos.start + '})/')
          content.noBuild = content.noBuild.replace(str,'$1 \r\n!['+ Checked[i].FileName + ']('+ BASE_IMAGE_URL + Checked[i].FileName + ')')
          setContent()
        }
      // 单图渲染
      }else if(Checked.length > 0)
      {
        let str = eval('/([\\w\\W]{' + pos.start + '})/')
        content.noBuild = content.noBuild.replace(str,'$1 \r\n!['+ Checked[0].FileName + ']('+ BASE_IMAGE_URL + Checked[0].FileName + ')')
        setContent()
      }
    }
    // 取消图片选择
    function CancelUploadFile(){
      UploadDialogVisible.value = false
    }

    // markdown效果显示
    let hljs = require('highlight.js'); // https://highlightjs.org/
    // 通常的默认值们
    let md = require('markdown-it')({
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return hljs.highlight(lang, str).value;
          } catch (__) {}
        }

        return ''; // 使用额外的默认转义
      }
    });

    // 将MarkDown文档转成HTML
    content.build = md.render(content.noBuild);

    // 重新渲染
    function setContent(){
      content.build = md.render(content.noBuild);
      emit('SaveMarkDown',content.noBuild);
    }

    // 获取选中文字首尾坐标
    function getPositionStartAndEnd(){
      let ctrl = document.getElementById("editor-content")
      let CaretPosStart,CaretPosEnd = 0;
      if(ctrl.selectionStart || ctrl.selectionStart == '0'){// Firefox support
        CaretPosStart = ctrl.selectionStart;
      }
      if(ctrl.selectionEnd || ctrl.selectionEnd == '0'){// Firefox support
        CaretPosEnd = ctrl.selectionEnd;
      }
      return {start:CaretPosStart,end:CaretPosEnd};
    }

    // 根据坐标替换指定内容
    function setContentToPosition(position,replace_content){
        let str = eval('/([\\w\\W]{' + position.start + '})/')
        content.noBuild = content.noBuild.replace(str,'$1'+replace_content)
        if(position.end != null)
        {
          let str2 = eval('/([\\w\\W]{' + position.end + '})/')
          content.noBuild = content.noBuild.replace(str2,'$1'+replace_content)
        }
        setContent()
    }

    // 上传附件
    function UploadFile(){
      ctx.$message.error("等我有空在做.")
    }

    // 代码块
    function setCode(Value){
      let codeRplCont = "```"
      let endNum = 5
      if(Value != "")
      {
        codeRplCont = codeRplCont+Value
        endNum = endNum + Value.length
      }
      let position = getPositionStartAndEnd()
      let str = eval('/([\\w\\W]{' + position.start + '})/')
      content.noBuild = content.noBuild.replace(str,'$1'+codeRplCont+'\r\n')
      let str2 = eval('/([\\w\\W]{' + (position.end+endNum) + '})/')
      content.noBuild = content.noBuild.replace(str2,'$1\r\n```')
      setContent()
    }

    /* 通用设置markdown标签语法
    @params end 是否尾部需要插入且加长
    @params replace_content  要根据坐标插入的内容
    **/
    function setTag(end,replace_content){

      let position = getPositionStartAndEnd()
      if(end === null)
      {
        position.end = end
      }else
      {
        position.end = position.end + end
      }
      setContentToPosition(position,replace_content)
    }

    return {
      full,
      Checked,
      content,
      SaveUploadFile,
      CancelUploadFile,
      UploadDialogVisible,
      // 实时重新渲染
      setContent,
      // 编辑按钮相关
      setTag,
      setCode,
      UploadFile,
      setContentToPosition,
      getPositionStartAndEnd,
      // 代码块下拉
      CodeOptions,
      CodeOptionsValue
    }
  }
}
</script>
<style scoped>
i{
  margin:10px;
  font-size: 18px;
}
i:hover{
  cursor:pointer
}
.nofull{
  height: 60vh;
  padding-bottom:20px
}
.full{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 998;
}
.text-content{
  height:96%
}
.editor-tool-position{
  position:-webkit-sticky;
  position:-moz-sticky;
  position:-ms-sticky;
  position:sticky;
  top:0;
  left:0;
  z-index:999;
}
.editor-tool{
  height: 35px;
  z-index: 999;
  vertical-align: bottom;
  margin: 0 auto;
  text-align: left;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}
.editor-tool-icon{
  margin:0 10px 10px 10px;
  font-size: 18px;
  font-weight: blod;
  display:inline-block;
}
.editor-tool-icon:hover{
  cursor:pointer
}
.editor-content,.editor-build-content{
  height: 100%;
  text-align: left;
  border:none;
  resize: none;
  width: 100%;
  overflow-y: scroll;
  box-shadow:none;
  border-right: 1px solid #a1a3a9;
  outline: none;
}
/* .editor-build-content{
  height: 70vh;
} */
.el-col{
  background-color: #FFFFFF;
}
.editor-content::-webkit-scrollbar, .editor-build-content::-webkit-scrollbar{
  width: 6px;
  height: 30px;
}
/* 滚动条的滑块 */
.editor-content::-webkit-scrollbar-thumb ,.editor-build-content::-webkit-scrollbar-thumb{
  background-color: #a1a3a9;
  border-radius: 3px;
}
</style>
